﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.NetworkInformation;
using System.Xml;
using mediaFunction;


namespace clientPC
{
    class Program
    {
        static void Main(string[] args)
        {
            bool paused = false;
            bool temp_pause = false ;
            string pause_status = "False";
            string temp_pause_interval = "0";
            int pause_interval=0;
            int new_pause_interval;
            int timeout = 300;
              
            sabnzbdAccess accessHandle = new sabnzbdAccess("192.168.1.64", "8080", "d9244b753a5bc874e91bc59ed6430baf");
            xmlHandler myXmlHandler = new xmlHandler();
            XmlTextReader sabnzbdStatus = accessHandle.xmlDump();

            //declarations and functions for pinging client PC            
            IPAddress ServerAddr = IPAddress.Parse("192.168.1.64");
            Ping pingSender = new Ping();
            PingReply reply = pingSender.Send(ServerAddr, timeout);
            bool serverOff = reply.Status != IPStatus.Success;

            if (!serverOff)
            {
                paused = myXmlHandler.findValue(sabnzbdStatus, "paused", ref pause_status);
                temp_pause = myXmlHandler.findValue(sabnzbdStatus, "pause_int", ref temp_pause_interval);
            }

            if (temp_pause)
            {
                pause_interval = (int)System.Convert.ToDecimal(temp_pause_interval.Replace(":", "."));
            }

            /*
             * default pause interval is 3 minutes
             * 3 minutes will be used if no arguments are supplied
             */
            new_pause_interval = 3;
            if (args.Length > 0)
            {
                new_pause_interval = int.Parse(args[0]);
            }

            /*
             * found the pause node
             */
            if (paused)
            {
                /*
                 * 1.  if sab has not been paused, pause for the new interval
                 * 2.  if sab is already paused...
                 * 2a. if it is a permanent pause, do nothing
                 * 2b. if the pause is less than new pause interval at the time of checking, revert to new pause interval
                 * 2c. if the pause is more than new pause interval at the time of checking, do nothing
                 */
                if (String.Compare(pause_status, "True") == 0)
                {
                    
                    if ((pause_interval < new_pause_interval) && (pause_interval > 0))
                    {
                        accessHandle.sabnzbdPause(new_pause_interval);
                    } 
                    
                }
                else
                {
                    accessHandle.sabnzbdPause(new_pause_interval);
                }
            }

        }
        
    }
}
